class Game {
  constructor() {
    this.sky = new Sky(-100);
    this.land = new Land(-100);
    this.bird = new Bird();
    this.pipePairProducer = new PipePairProducer(-100);
    this.mask = new Mask();
    this.timer = null;
    // 移动的时间间隔
    this.tick = 16;
    this.gameOver = false;
  }

  startGame() {
    if (this.timer) {
      return;
    }
    if (this.gameOver) {
      window.location.reload();
    }
    this.mask.hideMask();
    this.bird.startSwing();
    this.pipePairProducer.startProducer();
    this.timer = setInterval(() => {
      const duration = this.tick / 1000;
      this.sky.move(duration);
      this.land.move(duration);
      this.bird.move(duration);
      this.pipePairProducer.pipePairs.forEach((pipePair) => {
        pipePair.move(duration);
      });
      if (this.getIsGameOver()) {
        this.gameOver = true;
        this.stopGame();
      }
    }, this.tick);
  }

  stopGame() {
    clearInterval(this.timer);
    this.timer = null;
    this.bird.stopSwing();
    this.pipePairProducer.stopProducer();

    let tipInfo = "游戏已暂停，按Enter键继续";
    if (this.gameOver) {
      tipInfo = "游戏结束，按Enter键重新开始";
    }
    this.mask.changeTipText(tipInfo);
    this.mask.showMask();
  }

  // 获取两个矩形是否发生碰撞接触
  getIsHit(rec1, rec2) {
    const center1X = rec1.left + rec1.width / 2;
    const center1Y = rec1.top + rec1.height / 2;
    const center2X = rec2.left + rec2.width / 2;
    const center2Y = rec2.top + rec2.height / 2;
    const disX = Math.abs(center1X - center2X);
    const disY = Math.abs(center1Y - center2Y);
    if (
      (rec1.width + rec2.width) / 2 > disX &&
      (rec1.height + rec2.height) / 2 > disY
    ) {
      return true;
    }
    return false;
  }

  getIsGameOver() {
    // 小鸟碰到地面
    if (this.bird.top === this.bird.maxMoveY) {
      return true;
    }
    // 小鸟是否和 "水管"对发生碰撞
    for (let i = 0; i < this.pipePairProducer.pipePairs.length; i++) {
      const item = this.pipePairProducer.pipePairs[i];
      if (
        this.getIsHit(this.bird, item.upPipe) ||
        this.getIsHit(this.bird, item.downPipe)
      ) {
        console.log("小鸟碰到水管");
        return true;
      }
    }
    return false;
  }

  regEvents() {
    window.onkeydown = (ev) => {
      if (ev.code === "Enter") {
        if (this.timer) {
          this.stopGame();
        } else {
          this.startGame();
        }
      }
      if (ev.code === "Space") {
        this.bird.jump();
      }
    };
  }
}

const game = new Game();
game.regEvents();
// console.log("game", game);
